package io.zhzhy.licensejwtdemo.license;

import java.util.HashMap;
import java.util.Map;

public class LZWUtil {
    public static String compress(String uncompressed) {
        int dictionarySize = 256;
        Map<String, Integer> dictionary = new HashMap<>();

        for (int i = 0; i < dictionarySize; i++) {
            dictionary.put(Character.toString((char) i), i);
        }

        String current = "";
        String compressed = "";
        for (char c : uncompressed.toCharArray()) {
            String combined = current + c;
            if (dictionary.containsKey(combined)) {
                current = combined;
            } else {
                compressed += dictionary.get(current) + " ";
                if (dictionarySize < 65536) {
                    dictionary.put(combined, dictionarySize++);
                }
                current = Character.toString(c);
            }
        }

        if (!current.equals("")) {
            compressed += dictionary.get(current);
        }

        return compressed.trim();
    }

    public static String decompress(String compressed) {
        int dictionarySize = 256;
        Map<Integer, String> dictionary = new HashMap<>();

        for (int i = 0; i < dictionarySize; i++) {
            dictionary.put(i, Character.toString((char) i));
        }

        String[] compressedArray = compressed.split(" ");
        int[] compressedInts = new int[compressedArray.length];
        for (int i = 0; i < compressedArray.length; i++) {
            compressedInts[i] = Integer.parseInt(compressedArray[i]);
        }

        String current = dictionary.get(compressedInts[0]);
        String decompressed = current;

        for (int i = 1; i < compressedInts.length; i++) {
            String previous = current;
            if (dictionary.containsKey(compressedInts[i])) {
                current = dictionary.get(compressedInts[i]);
                decompressed += current;
                if (dictionarySize < 65536) {
                    dictionary.put(dictionarySize++, previous + current.charAt(0));
                }
            } else {
                current = previous + previous.charAt(0);
                decompressed += current;
                dictionary.put(dictionarySize++, current);
            }
        }

        return decompressed;
    }


}
